package com.ang.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.ang.base.Constants;
import com.ang.domain.Product;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/delete")
public class DeleteController {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 提供删除文档
     */
    @RequestMapping("/insert")
    public void insert() throws IOException {
        Product p = new Product("id1002", "删除", "p30", "手机", 100000, 5999.0, DateUtil.date());

        String index = Constants.ES_INDEX_PRODUCT;

        IndexRequest indexRequest = new IndexRequest(index);
        indexRequest.source(JSON.toJSONString(p), XContentType.JSON);
        //设置操作类型，false时，_id相同会覆盖，true会报错
        indexRequest.create(true);
        //设置 _id
        indexRequest.id("_id1002");

        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    }

    /**
     * 单个删除
     */
    @RequestMapping("/deleteSingle")
    public void deleteSingle() throws IOException {
//        DeleteRequest deleteRequest = new DeleteRequest(Constants.ES_INDEX_PRODUCT, "_id1002");
        DeleteRequest deleteRequest = new DeleteRequest();
        deleteRequest.id("_id1002");
        deleteRequest.index(Constants.ES_INDEX_PRODUCT);

        restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
    }

    /**
     * 条件删除:DeleteByQueryRequest
     */
    public void deleteByCondition() throws IOException {
//        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(Constants.ES_INDEX_PRODUCT);
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        deleteByQueryRequest.indices(Constants.ES_INDEX_PRODUCT);
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name","删除");
        deleteByQueryRequest.setQuery(matchQueryBuilder);

        restHighLevelClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
    }
}
